package com.demo.swingquickticket.service;

import com.demo.swingquickticket.entity.Account;
import com.demo.swingquickticket.entity.Order;
import com.demo.swingquickticket.entity.Station;
import com.demo.swingquickticket.util.SerializeUtil;
import com.demo.swingquickticket.util.SpringUtils;
import com.demo.swingquickticket.util.redis.CacheUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
public class DataService {

    private static StationService stationService = SpringUtils.getBean("stationService");

    private static CacheUtil cacheUtil = SpringUtils.getBean("cacheUtil");

    private static Map<String, List<Station>> stationList;

    private static Account account;

    private static Map<String, Order> workMap = new ConcurrentHashMap<>();

    private static LinkedBlockingQueue<Order> orderQueue = new LinkedBlockingQueue<>();

    public static Map<String, List<Station>> getStationList() {
        if (stationList == null) {
            stationList = stationService.initStationList();
        }
        return stationList;
    }

    public static Account getAccount() {
        if (account == null) {
            account = (Account) SerializeUtil.unSerialize(cacheUtil.getBytes("account"));
            if (account == null) {
                account = new Account();
            }
        }
        return account;
    }

    public static void saveAccount() {
        cacheUtil.setBytes("account", SerializeUtil.serialize(account));
    }

    public static void addWork(Order order) {
        log.info("添加任务:{}", order);
        workMap.put(order.getMark(), order);
        putWorkQueue(order);
    }

    public static void stopWork(String mark) {
        Order order = workMap.get(mark);
        if (order != null) {
            log.info("停止任务,编号:{}", mark);
            order.setWorkStatus(Order.STOP);
        }
    }

    public static void startWork(String mark) {
        Order order = workMap.get(mark);
        if (order != null) {
            if (order.getWorkStatus() == Order.STOP) {
                log.info("开始任务,编号:{}", mark);
                order.setWorkStatus(Order.START);
                putWorkQueue(order);
            }
        }
    }

    public static void removeWork(String mark) {
        log.info("移除任务,编号:{}", mark);
        workMap.remove(mark);
    }

    public static boolean existWork(String mark) {
        return workMap.containsKey(mark);
    }

    public static void putWorkQueue(Order order) {
        try {
            orderQueue.put(order);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Order takeWorkQueue() {
        try {
            return orderQueue.take();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
